##########
# Crossing Borders: Ticino Parliament
#########

rm(list = ls())

library(lfe)
library(texreg)
library(tidyverse)
library(lmtest)
library(data.table)
library(cowplot)
library(patchwork)
library(here)
library(qs)

ticino <- qread(here("data", "ticino_parliament_main.qs"))

ticino <- ticino %>% filter(year >= 1992 & year <= 2021)

source(here("code", "functions.R"))

ticino %>% group_by(id) %>% summarise(max_imm = max(immigration_handcoded)) %>% pull(max_imm) %>% sum

ticino %>% group_by(id) %>% summarise(n = n()) %>% pull(n) %>% table
# Main Results: -------------------------------------------------------------------
#Share of immigration-related bills to totall bills in both border regions
ticino <- ticino %>% 
  mutate(border_region = recode(border, "1" = "0-15 minutes", "0" = "15-30 minutes"))

## Trends -------------------------------------------------------------------
p1 <- ticino %>% 
  ggplot(aes(x = year, y = immigration_handcoded, color = border_region, fill = border_region, group = border_region,
             linetype = border_region, shape = border_region)) + 
  stat_summary(fun.y = mean, geom = "point") + 
  geom_smooth(method = "loess") + 
  geom_vline(xintercept = c(1999, 2004), linetype = "dashed", color = "black") +
  ylab("Share of immigration-related bills") +
  xlab("Year") +
  theme_minimal() + 
  scale_x_continuous(breaks = seq(1992, 2020, 2), labels = seq(1992, 2020, 2) %>% str_sub(3, 4),
                     expand = expansion(mult = 0, add = 0.5)) +
  scale_color_manual(values = cbPalette[-3], name = NULL, guide = "legend") +
  scale_fill_manual(values = cbPalette[-3], name = NULL, guide = "legend") +
  scale_linetype_manual(values = c("solid", "dashed", "dotted"), name = NULL, guide = "legend") +
  scale_shape_manual(values = c(16, 17, 18), name = NULL, guide = "legend") +
  scale_y_continuous(breaks = seq(0, 0.08, 0.01)) +
  annotate("text", x = 1995, y = .06, label = "Pre-Reform", hjust = 0.5) +
  annotate("text", x = 2001.5, y = .06, label = "Transition", hjust = 0.5) +
  annotate("text", x = 2011.25, y = .06, label = "Free Movement", hjust = 0.5) +
  theme(legend.position = "bottom",
        legend.background = element_rect(color = "black"),
        legend.margin = margin(4,4,4,4,unit = "pt"),
        axis.title.y = element_text(vjust = 0)) +
  ggtitle("A. Immigrant-Related Bills by Region")

## DiD -------------------------------------------------------------------
mod_ticino_did <- felm(immigration_handcoded ~ transition_border + free_border | as.factor(year) + border | 0 |id, data = ticino)



p2 <- ggplot(coef.gg.prep(list(mod_ticino_did)), aes(x = modelcoef, y = -1*y, xmin = ylo95, xmax = yhi95, color = variable, shape = variable, group = variable)) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  ggstance::geom_linerangeh(position = ggstance::position_dodgev(.25)) +
  ggstance::geom_pointrangeh(aes(xmin = ylo90, xmax = yhi90), size = 1.25, position = ggstance::position_dodgev(.25)) +
  ylab(NULL) +
  scale_y_continuous(breaks = c(-2, -1), labels = c("Transition\nPeriod", "Free\nMovement"), expand = expand_scale(mult = 0, add = 0.5)) +
  scale_color_manual(name = NULL, guide = "none", values = cbPalette[-3]) +
  scale_shape_discrete(name = NULL, guide = "none") +
  xlab("Effect of Border Proximity on Immigrant-Related Bills") +
  ggtitle("C. Difference-in-Differences Estimates") +
  theme_bw() + 
  theme(legend.position = "bottom",
        legend.background = element_rect(color = "black"),
        legend.margin = margin(4,4,4,4,unit = "pt"))


## Event Study -------------------------------------------------------------
fmla <- as.formula(
  paste0(
    "immigration_handcoded ~ ",
    paste0("border_", c(1992:1998, 2000:2021), collapse = " + "),
    " | as.factor(year) + border | 0 | id")
)

mod_ticino_es = felm(fmla, data = ticino)

event_study_dat <- data.frame(
  y = coef(mod_ticino_es),
  ymin = coef(mod_ticino_es) - qt(.975, df = df.residual(mod_ticino_es))*sqrt(diag(vcov(mod_ticino_es))),
  ymax = coef(mod_ticino_es) + qt(.975, df = df.residual(mod_ticino_es))*sqrt(diag(vcov(mod_ticino_es))),
  Year = as.numeric(gsub("border_", "", names(coefficients(mod_ticino_es))))
)

event_study_dat <- rbind(setDT(event_study_dat), data.table(c(0), c(0), c(0), c(1999)), use.names = F) %>% filter(complete.cases(Year))

plot_ticino_es <- ggplot(data = event_study_dat, aes(x = Year, y = y, ymin = ymin, ymax = ymax, 
                                                     color = factor(ifelse(Year <= 1999, 3, ifelse(Year < 2004, 2, 1))),
                                                     shape = factor(ifelse(Year <= 1999, 3, ifelse(Year < 2004, 2, 1)))
                                                     )) +
  geom_vline(xintercept = c(1999, 2004), linetype = 2, color = "black") +
  geom_hline(yintercept = 0, linetype = 2, color = "black") +
  geom_pointrange() +
  annotate("text", x = 1994.5, y = 0.07, label = "Pre-Reform", hjust = 0.5) +
  annotate("text", x = 2001.5, y = 0.07, label = "Transition", hjust = 0.5) +
  annotate("text", x = 2011.75, y = 0.07, label = "Free Movement", hjust = 0.5) +
  scale_color_manual(values = cbPalette[c(1,2,8)], name = NULL, labels = c("Free Movement", "Transition", "Pre-Reform"), guide = guide_legend(reverse = T)) +
  scale_shape_manual(values = c(16, 17, 18), 
                     name = NULL, 
                     labels = c("Free Movement", "Transition", "Pre-Reform"), 
                     guide = guide_legend(reverse = T)) + 
  ylab("Change in Immigration-Related Bills") +
  theme_minimal() +
  scale_x_continuous(breaks = seq(1992, 2022, 2), labels = seq(1992, 2022, 2) %>% str_sub(3, 4)) +
  theme(legend.position = "bottom",
        legend.background = element_rect(color = "black"),
        legend.margin = margin(4,4,4,4,unit = "pt")) +
  ggtitle("B. Annual Effects of Border Opening")


#Output figures
plots <- align_patches(p1, p2)
top_row <- plot_grid(plots[[1]], plot_ticino_es, align = "h")
pdf(here("figures", "Fig9.pdf"), height = 8.27, width = 11.69)
plot_grid(top_row, plots[[2]], ncol = 1, rel_heights = c(3, 1.5))
dev.off()



# By Region ---------------------------------------------------------------
#Share of immigration-related bills to bills in each border regions
ticino_region <- qread(here("data", "ticino_parliament_byregion.qs"))

ticino_region <- ticino_region %>% filter(year >= 1992 & year <= 2021)

ticino_region <- ticino_region %>% 
  mutate(border_region = recode(border, "1" = "0-15 minutes", "0" = "15-30 minutes"))



ticino_region %>% group_by(id) %>% summarise(max_imm = max(immigration_handcoded)) %>% pull(max_imm) %>% sum

## Trends ------------------------------------------------------------------
p1_region <- ticino_region %>% 
  ggplot(aes(x = year, y = immigration_handcoded, color = border_region, fill = border_region, group = border_region)) + 
  stat_summary(fun.y = mean, geom = "point") + 
  geom_smooth(method = "loess") + 
  geom_vline(xintercept = c(1999, 2004), linetype = "dashed", color = "black") +
  ylab("Share of immigration-related bills") +
  xlab("Year") +
  theme_minimal() + 
  scale_x_continuous(breaks = seq(1992, 2020, 2), labels = seq(1992, 2020, 2) %>% str_sub(3, 4),
                     expand = expand_scale(mult = 0, add = 0.5)) +
  scale_y_continuous(breaks = seq(0, 0.08, 0.01)) +
  scale_color_manual(values = cbPalette[-3], name = NULL) +
  scale_fill_manual(values = cbPalette[-3], name = NULL) +
  annotate("text", x = 1995, y = .08, label = "Pre-Reform", hjust = 0.5) +
  annotate("text", x = 2001.5, y = .08, label = "Transition", hjust = 0.5) +
  annotate("text", x = 2011.25, y = .08, label = "Free Movement", hjust = 0.5) +
  theme(legend.position = "bottom",
        legend.background = element_rect(color = "black"),
        legend.margin = margin(4,4,4,4,unit = "pt"),
        axis.title.y = element_text(vjust = 0)) +
  ggtitle("A. Immigrant-Related Bills by Region")


## DiD ------------------------------------------------------------------
mod_ticino_did_region <- felm(immigration_handcoded ~ transition_border + free_border | border + as.factor(year) | 0 |id, data = ticino_region)

p2_region <- ggplot(coef.gg.prep(list(mod_ticino_did_region)), aes(x = modelcoef, y = -1*y, xmin = ylo95, xmax = yhi95, color = variable, shape = variable, group = variable)) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  ggstance::geom_linerangeh(position = ggstance::position_dodgev(.25)) +
  ggstance::geom_pointrangeh(aes(xmin = ylo90, xmax = yhi90), size = 1.25, position = ggstance::position_dodgev(.25)) +
  ylab(NULL) +
  scale_y_continuous(breaks = c(-2, -1), labels = c("Transition\nPeriod", "Free\nMovement"), expand = expand_scale(mult = 0, add = 0.5)) +
  scale_color_manual(name = NULL, guide = "none", values = cbPalette[-3]) +
  scale_shape_discrete(name = NULL, guide = "none") +
  xlab("Effect of Border Proximity on Immigrant-Related Bills") +
  ggtitle("C. Difference-in-Differences Estimates") +
  theme_bw() + 
  theme(legend.position = "bottom",
        legend.background = element_rect(color = "black"),
        legend.margin = margin(4,4,4,4,unit = "pt"))



## Event Study -------------------------------------------------------------
mod_ticino_es_region <- felm(fmla, data = ticino_region)

event_study_dat <- data.frame(
  y = coef(mod_ticino_es_region),
  ymin = coef(mod_ticino_es_region) - qt(.975, df = df.residual(mod_ticino_es_region))*sqrt(diag(vcov(mod_ticino_es_region))),
  ymax = coef(mod_ticino_es_region) + qt(.975, df = df.residual(mod_ticino_es_region))*sqrt(diag(vcov(mod_ticino_es_region))),
  Year = as.numeric(gsub("border_", "", names(coefficients(mod_ticino_es_region))))
)

event_study_dat <- rbind(setDT(event_study_dat), data.table(c(0), c(0), c(0), c(1999)), use.names = F) %>% filter(complete.cases(Year))

plot_ticino_es_region <- ggplot(data = event_study_dat, aes(x = Year, y = y, ymin = ymin, ymax = ymax, 
                                                            color = factor(ifelse(Year <= 1999, 3, ifelse(Year < 2004, 2, 1))),
                                                            shape = factor(ifelse(Year <= 1999, 3, ifelse(Year < 2004, 2, 1)))
                                                            )) +
  geom_vline(xintercept = c(1999, 2004), linetype = 2, color = "black") +
  geom_hline(yintercept = 0, linetype = 2, color = "black") +
  geom_pointrange() +
  annotate("text", x = 1994.5, y = 0.11, label = "Pre-Reform", hjust = 0.5) +
  annotate("text", x = 2001.5, y = 0.11, label = "Transition", hjust = 0.5) +
  annotate("text", x = 2011.75, y = 0.11, label = "Free Movement", hjust = 0.5) +
  scale_color_manual(values = cbPalette[c(1,2,8)], name = NULL, labels = c("Free Movement", "Transition", "Pre-Reform"), guide = guide_legend(reverse = T)) +
  scale_shape_manual(values = c(16, 17, 18), 
                     name = NULL, 
                     labels = c("Free Movement", "Transition", "Pre-Reform"), 
                     guide = guide_legend(reverse = T)) + 
  ylab("Change in Immigration-Related Bills") +
  theme_minimal() +
  scale_x_continuous(breaks = seq(1992, 2020, 2), labels = seq(1992, 2020, 2) %>% str_sub(3, 4)) +
  theme(legend.position = "bottom",
        legend.background = element_rect(color = "black"),
        legend.margin = margin(4,4,4,4,unit = "pt")) +
  ggtitle("B. Annual Effects of Border Opening")

plots <- align_patches(p1_region, p2_region)
top_row <- plot_grid(plots[[1]], plot_ticino_es_region, align = "h")
pdf(here("figures", "TicinobyRegion.pdf"), height = 8.27, width = 11.69)
plot_grid(top_row, plots[[2]], ncol = 1, rel_heights = c(3, 1.5))
dev.off()


# far right ---------------------------------------------------------------
ticino_region <- ticino_region %>% 
  mutate(border_region = recode(border, "1" = "0-15 minutes", "0" = "15-30 minutes"))

#Trends by Far-Right sponsors
ticino_region %>% 
  mutate(fr_parties = case_when(fr_parties == 0 ~ "B. Other Parties", TRUE ~ "A. Far-Right Parties")) %>% 
  ggplot(aes(x = year, y = immigration_handcoded, color = border_region, fill = border_region, group = border_region, linetype = border_region, shape = border_region)) + 
  stat_summary(fun.y = mean, geom = "point") + 
  geom_smooth(method = "loess") + 
  geom_vline(xintercept = c(1999, 2004), linetype = "dashed", color = "black") +
  ylab("Share of immigration-related bills") +
  xlab("Year") +
  theme_minimal() + 
  facet_wrap(~ fr_parties) + 
  scale_x_continuous(breaks = seq(1992, 2020, 2), labels = seq(1992, 2020, 2) %>% str_sub(3, 4),
                     expand = expansion(mult = 0, add = 0.5)) +
  scale_color_manual(values = cbPalette[-3], name = NULL, guide = "legend") +
  scale_fill_manual(values = cbPalette[-3], name = NULL, guide = "legend") +
  scale_linetype_manual(values = c("solid", "dashed", "dotted"), name = NULL, guide = "legend") +
  scale_shape_manual(values = c(16, 17, 18), name = NULL, guide = "legend") +
  annotate("text", x = 1995, y = .12, label = "Pre-Reform", hjust = 0.5) +
  annotate("text", x = 2001.5, y = .12, label = "Transition", hjust = 0.5) +
  annotate("text", x = 2009.25, y = .12, label = "Free Movement", hjust = 0.5) +
  theme(legend.position = "bottom",
        legend.background = element_rect(color = "black"),
        legend.margin = margin(4,4,4,4,unit = "pt"),
        axis.title.y = element_text(vjust = 0), strip.text = element_text(size = 12)) +
  ggtitle("Immigrant-Related Bills by Region and Far-Right Party")
ggsave(here("figures", "TicinoRegionParty.pdf"), width = 10, height = 6)


# Regression outputs ------------------------------------------------------
mod_ticino_did
mod_ticino_did_region

mod_ticino_es
mod_ticino_es_region

Texreg(
  list(
    mod_ticino_did,
    mod_ticino_es,
    mod_ticino_did_region,
    mod_ticino_es_region
  ),
  custom.header = list("Relative to All bills" = 1:2, "Relative to Bills in Region" = 3:4),
  custom.gof.names = c("Num. obs.", "Num.groups: year", "Num.groups: border"),
  custom.coef.map = list(
    "transition_border" = "0--15 Minutes X Transition",
    "free_border" = "0--15 Minutes X Free",
    "border_1996" = "0--15 Minutes X 1996",
    "border_1997" = "0--15 Minutes X 1997",
    "border_1998" = "0--15 Minutes X 1998",
    "border_2000" = "0--15 Minutes X 2000",
    "border_2001" = "0--15 Minutes X 2001",
    "border_2002" = "0--15 Minutes X 2002",
    "border_2003" = "0--15 Minutes X 2003",
    "border_2004" = "0--15 Minutes X 2004",
    "border_2005" = "0--15 Minutes X 2005",
    "border_2006" = "0--15 Minutes X 2006",
    "border_2007" = "0--15 Minutes X 2007",
    "border_2008" = "0--15 Minutes X 2008",
    "border_2009" = "0--15 Minutes X 2009",
    "border_2010" = "0--15 Minutes X 2010",
    "border_2011" = "0--15 Minutes X 2011",
    "border_2012" = "0--15 Minutes X 2012",
    "border_2013" = "0--15 Minutes X 2013",
    "border_2014" = "0--15 Minutes X 2014",
    "border_2015" = "0--15 Minutes X 2015",
    "border_2016" = "0--15 Minutes X 2016"
  ),
  caption = "Effects on Immigrant-Related Parliamentary Bills in Ticino. Outcome: Immigration-Related Bills per Region Relative to All Bills in Municipalities Within 0--30 Minutes from Border Crossings in Ticino (Models 1 and 2) and Immigration-Related Bills per Region Relative to All Bills in That Specific Region Only (0--15 Minutes from Border Crossings as One Region and 15--30 Minutes as Another Region) (Models 3 and 4). Sample: Border Region, Travel Minutes $<=$ 30, 1992--2021 in Ticino. Baseline Year: 1999.",
  label = "tab:ticino_main",
  file = here("tables", "ticino_main.tex"),
  single.row = T
)

